﻿using System;

namespace MyLib.Web {
	/// <summary>
	/// 
	/// </summary>
	public static class ControlExtensions {
		/// <summary>
		/// 
		/// </summary>
		/// <param name="control"></param>
		/// <param name="name"></param>
		/// <returns></returns>
		public static System.Web.UI.Control FindDescendantControl(this System.Web.UI.Control control, string name) {
			if (control == null)
				throw new ArgumentNullException("control");

			if (string.IsNullOrWhiteSpace(name))
				throw new ArgumentNullException("name");

			var names = name.Split('.');

			var c = control;
			for (int i = 0; i < names.Length; ++i) {
				var cc = c.FindControl(names[i]);

				if (cc == null)
					throw new InvalidOperationException(
						string.Format("Cannot find child control \"{0}\" of \"{1}\" in container \"{2}\".", names[i], c.ID, control.ID));

				c = cc;
			} // end of for.

			return c;
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="control"></param>
		/// <param name="name"></param>
		/// <returns></returns>
		public static System.Web.UI.Control FindSiblingControl(this System.Web.UI.Control control, string name) {
			if (control == null)
				throw new ArgumentNullException("control");

			if (string.IsNullOrWhiteSpace(name))
				throw new ArgumentNullException("name");

			var c = control;
			while (c != null) {
				c = c.Parent;

				if (c is System.Web.UI.INamingContainer) {
					return c.FindDescendantControl(name);
				}
			}

			return null;
		}
	} // end of ControlExtensions.
}
